<template>
  <jke-modal
      :visible.sync="jkeForm.visible"
      :width="1200"
      :title="jkeForm.title"
      :fullscreen.sync="jkeForm.fullscreen"
      :switchFullscreen="jkeForm.switchFullscreen"
    >
    <!--  -->
    <crumbs @goBack="goBack" :superiorMenu="['销售管理', '客户管理']" :currentMenu="jkeForm.title"></crumbs>
    <div class="form-body">
      <a-card title="基础信息" :bordered="false" style="margin-top: 12px">
        <a-form :form="form" @submit="handleSubmit" layout="vertical">
          <!-- <a-form-item label="工艺编号" required>
            <a-input v-decorator="['customerCode']" placeholder="不输入则自动生成" />
          </a-form-item> -->
          <a-form-item label="客户编号" required>
            <a-input
              v-decorator="[
                'customerCode',
                {
                  rules: [
                    {
                      required: true,
                      message: '请输入客户编号或自动生成',
                    },
                    {
                      message: '该值不可用，系统中已存在！',
                      validator: (rule, value, callback) =>
                        validateDuplicateValue('ERP_CUSTOMER', 'customer_code', value, queryId, callback),
                    },
                  ],
                },
              ]"
              placeholder="不输入则自动生成"
            />
            <span class="btn-text code-btn" @click="genEntityCode" v-if="!isEdit">自动生成</span>
          </a-form-item>
          <a-form-item label="客户简称">
            <a-input
              :maxLength="8"
              v-decorator="[
                'customerShortName',
                {
                  rules: [
                    { required: true, message: '请输入客户简称' },
                    {
                      message: '该值不可用，系统中已存在！',
                      validator: (rule, value, callback) =>
                        validateDuplicateValue('ERP_CUSTOMER', 'customer_short_name', value, queryId, callback),
                    },
                  ],
                },
              ]"
              placeholder="请输入客户简称"
            />
          </a-form-item>
          <a-form-item label="客户全称">
            <a-input
              :maxLength="15"
              @input="handleInput"
              v-decorator="[
                'customerFullName',
                {
                  rules: [
                    { required: true, message: '请输入客户全称' },
                    {
                      message: '该值不可用，系统中已存在！',
                      validator: (rule, value, callback) =>
                        validateDuplicateValue('ERP_CUSTOMER', 'customer_full_name', value, queryId, callback),
                    },
                  ],
                },
              ]"
              placeholder="请输入客户全称"
            />
          </a-form-item>
        </a-form>
        <a-form :form="form" @submit="handleSubmit" layout="vertical">
          <a-form-item label="是否录入开票信息">
            <a-select
              v-decorator="['isInputInvoice', { rules: [{ required: true, message: '请选择' }] }]"
              placeholder="请选择"
              @change="isInputInvoiceChange"
            >
              <a-select-option value="yes">是</a-select-option>
              <a-select-option value="no">否</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="是否录入客户联系人">
            <a-select
              v-decorator="['isInputContacts', { rules: [{ required: true, message: '请选择' }] }]"
              placeholder="请选择"
            >
              <a-select-option value="yes">是</a-select-option>
              <a-select-option value="no">否</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item> </a-form-item>
        </a-form>
      </a-card>
      <a-card v-if="isInputInvoice" title="开票信息" :bordered="false" style="margin-top: 12px">
        <a-form :form="form" @submit="handleSubmit" layout="vertical">
          <a-form-item label="公司名称">
            <a-input
              v-decorator="['companyName', { rules: [{ required: true, message: '请输入公司名称' }] }]"
              placeholder="请输入公司名称"
            />
          </a-form-item>
          <a-form-item label="纳税人识别号">
            <a-input
              v-decorator="[
                'taxDiscernNum',
                {
                  rules: [
                    { required: true, message: '请输入纳税人识别号' }, //正则校验纳税人识别号
                    {
                      pattern: /^([0-9A-HJ-NPQRTUWXY]{2})([0-9ABCDEFGHJKLMNPQRTUWXY]{6})([0-9A-HJ-NPQRTUWXY]{9})([0-9A-HJ-NPQRTUWXY]{1})$/,
                      message: '请输入正确的纳税人识别号',
                    },
                  ],
                },
              ]"
              placeholder="请输入纳税人识别号"
            />
          </a-form-item>
          <a-form-item label="地址">
            <a-input
              v-decorator="[
                'address',
                {
                  rules: [
                    { required: true, message: '请输入地址' },
                    //地址正则校验
                    {
                      pattern: /^[\u4e00-\u9fa5a-zA-Z0-9\s\,\，\。\、\.]{0,100}$/,
                      message: '请输入正确的地址',
                    },
                  ],
                },
              ]"
              placeholder="请输入地址"
            />
          </a-form-item>
        </a-form>
        <a-form :form="form" @submit="handleSubmit" layout="vertical">
          <a-form-item label="电话">
            <a-input
              v-decorator="[
                'phone',
                {
                  rules: [
                    { required: true, message: '请输入电话' },
                    // 手机号码及座机电话正则校验
                    {
                      pattern: /^((0\d{2,3}-\d{7,8})|(1[35849]\d{9}))$/,
                      message: '请输入正确的电话号码',
                    },
                  ],
                },
              ]"
              placeholder="请输入电话"
            />
          </a-form-item>
          <a-form-item label="开户行">
            <a-input
              v-decorator="['bankName', { rules: [{ required: true, message: '请输入开户行' }] }]"
              :maxLength="50"
              placeholder="请输入开户行"
            />
          </a-form-item>
          <a-form-item label="账号">
            <a-input
              v-decorator="[
                'accountNumber',
                {
                  rules: [
                    { required: true, message: '请输入账号' },
                    //银行账号校验
                    {
                      pattern: /^[0-9]{0,30}$/,
                      message: '请输入正确的银行账号',
                    },
                  ],
                },
              ]"
              placeholder="请输入账号"
            />
          </a-form-item>
        </a-form>
      </a-card>
      <a-card
        v-if="form.getFieldValue('isInputContacts') == 'yes'"
        title="客户联系人"
        :bordered="false"
        style="margin-top: 12px"
      >
        <a-col :span="24" style="margin-bottom: 38px">
          <j-editable-table
            :ref="refKeys[0]"
            :loading="customer.loading"
            :rowNumber="true"
            :columns="customer.columns"
            :dataSource="customer.dataSource"
            :maxHeight="300"
            :disabled="formDisabled"
            :actionButton="true"
            @valueChange="valueChange"
          >

            <template v-slot:contactName="props">
              <a-input v-model="props.value" @blur="blurContactName(props)" placeholder="请输入" :maxLength="30" />
            </template>
            <template v-slot:contactPost="props">
              <a-input v-model="props.value" @blur="blurContactPost(props)" placeholder="请输入" :maxLength="30" />
            </template>

            <template v-slot:processId="props">
              <a-select
                :filter-option="filterOption"
                show-search
                @popupScroll="popupScroll"
                style="width: 100%"
                :not-found-content="processList.length > 0 ? null : '暂无数据'"
                :defaultValue="props.value"
                @select="(bl, e) => onChangeSelect(bl, props)"
              >
                <a-select-option v-for="(item, key) in processList" :key="key" :value="item.id">
                  <!-- <span style="display: inline-block; width: 100%" :title="item.processName"> -->
                  {{ item.processCode }}-{{ item.processName }}
                  <!-- </span> -->
                </a-select-option>
              </a-select>
            </template>
            <template v-slot:action="props">
              <!-- <a style="padding-left: 3px">编辑</a> -->
              <a-popconfirm
                title="是否删除?"
                ok-text="是"
                cancel-text="否"
                @confirm="handleDelete(props)"
                @cancel="cancel"
              >
                <a style="padding-left: 3px;color:#F25643">删除</a>
              </a-popconfirm>
            </template>
          </j-editable-table>
        </a-col>
      </a-card>
      <a-card title="其他信息" :bordered="false" style="margin-top: 12px">
        <a-form :form="form" @submit="handleSubmit" layout="vertical">
          <a-form-item label="客户经理" required prop="belongUserId">
            <j-select-user-by-dep
              v-model="signUser"
              v-decorator="['belongUserId', { rules: [{ required: true, message: '请选择客户经理' }] }]"
              @changeRow="userFilter"
              :seldep="true"
              :modalWidth="1000"
              :multi="false"
            ></j-select-user-by-dep>
          </a-form-item>
          <!-- <a-form-item label="备注" style="flex: 1">
            <a-textarea placeholder="请输入" :maxLength="500" auto-size v-decorator="['remark']" />
          </a-form-item> -->
        </a-form>
        <a-form layout="vertical">
          <a-form-item label="附件" style="flex: 1">
            <file-upload :ids="attachment" @getFileList="getFileList"></file-upload>
            <p style="line-height: 30px;color:#8d8d8d;">最多上传5个文件，每个大小不可超过20M</p>
          </a-form-item>
        </a-form>
      </a-card>
      <div style="margin-top: 12px" v-if="examineType == '0'">
        <Examine @submitProcess="submitProcess" :type="examineType" id="ERP_CUSTOMER" ref="examine" />
        <div style="height: 50px"></div>
      </div>
    </div>

    <div class="footer-submit form-footer">
      <a-button @click="goBack" class="submitBtn" style="margin-right: 10px"> 取消 </a-button>
      <a-button type="primary" :loading="loadingSubmit" class="submitBtn" @click="submitProcess"> 提交 </a-button>
    </div>
  </jke-modal>
</template>
<script>
import { FormTypes } from '@/utils/JEditableTableUtil'
import crumbs from '@/components/crumbs.vue'
import {
  productCraftProcessRelAdd,
  productCraftProcessRelEdit,
  productCraftProcessRelById,
  getUserDict,
  getDictModel,
  getAllGoodsBaseInfo,
  productGetDictPageList,
  checkByGoodsIdt,
} from '@/api/goodsManagement'
import FileUpload from '@/components/fileActions/FileUpload.vue'
import Examine from '@/components/examine'
import { API } from '@/api/requestFzs'
import { APILX } from '@/api/requestLx'
import { validateDuplicateValue } from '@/utils/util'
import { fourFloatNum } from '@/utils/util'
import { validateCheckRule } from '@/utils/util'
export default {
  name: 'customerForm', //新建客户
  data() {
    return {
      jkeForm: {
        title: '新建客户',
        visible: false,
        fullscreen: true,
        switchFullscreen: true,
      },
      examineType: '0',
      signUser: '', //客户经理
      billShow: 'false', //是否开票
      processParam: {
        pageNo: 1,
        pageSize: 999,
      },
      validateDuplicateValue, //自动生成编码
      queryId: '',
      loadingSubmit: false, //防止多次提交
      submitApi: APILX.erpCustomerAdd,
      isEdit: false,
      attachment: '', //附件
      //
      refKeys: ['customer'],
      tableKeys: ['customer'],
      processList: [], //表格-工序 数据
      customer: {
        loading: false,
        dataSource: [{}],
        columns: [
          {
            title: '姓名',
            key: 'contactName',
            isrequired: true,
            type: FormTypes.slot,
            placeholder: '请输入',
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }],
          },
          {
            title: '职务',
            key: 'contactPost',
            isrequired: true,
            type: FormTypes.slot,
            placeholder: '请输入',
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }],
          },
          {
            title: '电话',
            key: 'contactPhone',
            isrequired: true,
            type: FormTypes.input,
            placeholder: '请输入',
            defaultValue: '',
            validateRules: [
              { required: true, message: '${title}不能为空' },

              // 手机号码及座机电话正则校验
              {
                // pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
                // message: '请输入正确的电话号码',
                handler(type, value, row, column, callback, target) {
                    // type 触发校验的类型（input、change、blur、getValues）
                    // value 当前校验的值
                    // callback(flag, message) 方法必须执行且只能执行一次
                    //          flag = 是否通过了校验，不填写或者填写 null 代表不进行任何操作
                    //          message = 提示的消息，默认使用配置的 message
                    // target 行编辑的实例对象
                    // console.log('value-----', value)
                    let reg1 = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
                    let reg2 = /^([0-9]{3,4}-)?[0-9]{7,8}$/;
                    console.log('reg1.test(value) || reg2.test(value)', reg1.test(value) || reg2.test(value))
                    if (reg1.test(value) || reg2.test(value)) {
                      callback(true)
                    } else {
                      callback(false, '请输入正确的电话号码或固话号码')
                    }
                },
              },
            ],
          },
          {
            title: '邮箱',
            key: 'contactEmail',
            type: FormTypes.input,
            placeholder: '请输入',
            defaultValue: '',
            validateRules: [
              // 邮箱正则校验
              {
                pattern: /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/,
                message: '请输入正确的邮箱',
              },
            ],
          },
          // validateRules: [
          //   {
          //     required: true, // 必填
          //     message: '${title}不能为空', // 提示的文本
          //   },
          //   // { pattern: /^[0-9]+(\.[0-9]{1,3})?$/, message: '请输入大于零的数字' },
          //   // { pattern: /^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/, message: '请输入大于零的数字' },
          //   // { pattern: /^(\-|\+)?\d+(\.\d+)?$/, message: '请输入大于零的数字' },
          //   { pattern: /^(([0-9]+)|([0-9]+\.[0-9]{0,2}))$/, message: '请输入大于零的数字（最多保留2位小数）' },
          //   // { pattern: /^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/, message: '请输入大于零的数字' },
          // ],
          // validateRules: [
          //   {
          //     // 自定义函数校验 handler
          //     handler(type, value, row, column, callback, target) {
          //       // type 触发校验的类型（input、change、blur、getValues）
          //       // value 当前校验的值
          //       // callback(flag, message) 方法必须执行且只能执行一次
          //       //          flag = 是否通过了校验，不填写或者填写 null 代表不进行任何操作
          //       //          message = 提示的消息，默认使用配置的 message
          //       // target 行编辑的实例对象

          //       if (type === 'change' || type === 'getValues') {
          //         console.log("153413213121321");
          //         let regular = /[^\d.]/g
          //         let regular2 = /^(\-)*(\d+)\.(\d{4}).*$/
          //           if (value) {

          //             console.log(regular.test(value),"0.0.0.0.");
          //             console.log(regular2.test(value),"0.0.0.0.222222");
          //             callback(false, '${title}不能是abc')

          //             // var newValue = this.fourFloatNum(value)
          //             // console.log(newValue, 'newValue')
          //           }

          //         if (value === 'abc') {
          //           callback(false, '${title}不能是abc') // false = 未通过，可以跟自定义提示
          //           return
          //         }

          //         // let { values } = target.getValuesSync({ validate: false })
          //         // console.log(value);
          //         // let count = 0
          //         // for (let val of values) {
          //         //     if (val['dbFieldName'] === value) {
          //         //         if (++count >= 2) {
          //         //             callback(false, '${title}不能重复')
          //         //             return
          //         //         }
          //         //     }
          //         // }
          //         callback(true) // true = 通过验证
          //       } else {
          //         callback() // 不填写或者填写 null 代表不进行任何操作
          //       }
          //     },
          //     message: '${title}默认提示',
          //   },
          // ],
          {
            title: '操作',
            width: '20%',
            key: 'action',
            type: FormTypes.slot,
            placeholder: '选择${title}',
            slotName: 'action',
            defaultValue: '',
          },
        ],
      },
      formLayout: 'horizontal',
      form: this.$form.createForm(this, { name: 'coordinated' }),
      isInputInvoice: false,
    }
  },
  components: {
    FileUpload,
    crumbs,
    Examine,
  },
  computed: {
    formDisabled() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return false
        }
        return true
      }
      return this.disabled
    },
  },
  methods: {
    blurContactName (props) {
      let x = this.refKeys[0]
      this.$refs[x].setValues([
        {
          rowKey: props.rowId, // 行的id
          values: {
            // 在这里 values 中的 goodsId 是你 columns 中配置的 key
            contactName: props.value
          },
        },
      ])
    },
    blurContactPost (props) {
      let x = this.refKeys[0]
      this.$refs[x].setValues([
        {
          rowKey: props.rowId, // 行的id
          values: {
            // 在这里 values 中的 goodsId 是你 columns 中配置的 key
            contactPost: props.value
          },
        },
      ])
    },
    checkName (rule, value, callback) {
      console.log('chufachufa')
      if (value.length = 0) {
        callback('请输入客户姓名！')
      }
      callback()
    },
    handleInput(e) {
      this.form.setFieldsValue({
        companyName: e.target.value,
      })
    },
    isInputInvoiceChange(e) {
      this.isInputInvoice = e == 'yes'
      var customerFullName = this.form.getFieldValue('customerFullName')
      setTimeout(() => {
        this.form.setFieldsValue({
          companyName: customerFullName,
        })
      }, 300)
    },
    /* 选人 */
    userFilter(v, row) {
      console.log(v, row)
      this.form.setFieldsValue({
        belongUserId: v,
      })
      if (row.length > 0) {
        this.signUser = row[0].id
      } else {
        this.signUser = ''
      }
    },
    // 下拉搜索
    filterOption(input, option) {
      console.log('inputoption', input, option)
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    /* 匹配正数,小数点后2位 */
    fourFloatNum(value) {
      //先把非数字的都替换掉，除了数字和.,
      // if (value.charAt(0) == 0 || value.charAt(0) == '.') {
      //   value = ''
      // }
      if (value.charAt(0) == '.') {
        value = ''
      }
      value = value.replace(/[^\d.]/g, '')
      value = value.replace(/^(\-)*(\d+)\.(\d{4}).*$/, '$1$2.$3')
      return value
    },
    // getDictModel() {
    //   // 类型字典
    //   let parameters = { dictCode: 'wms_goods_type' }
    //   getDictModel(parameters).then((res) => {
    //     if (res.code == 200) {
    //       this.typeList = res.result
    //       console.log(res, 'inStockStatus')
    //     }
    //   })
    // },
    // 工序 change
    onChangeSelect(bl, props) {
      console.log(props, 'props')
      var obj = this.processList.find((item) => {
        return item.id === bl
      })
      this.$refs.customer.setValues([
        {
          rowKey: props.rowId, // 行的id
          values: {
            // 在这里 values 中的 specifications 是你 columns 中配置的 key
            processId: bl,
            processWorkUnit: obj.processWorkUnit || '',
            processRequire: obj.processRequire || '',
          },
        },
      ])
      const { error, values } = this.$refs.customer.getValuesSync({ validate: true })
      console.log(values, 'valuesvaluesvalues')
    },
    getProcess() {
      productGetDictPageList(this.processParam).then((res) => {
        res.result.records.forEach((item) => {
          this.processList.push(item)
        })
      })
    },
    popupScroll(e) {
      const { scrollHeight, scrollTop, clientHeight } = e.target
      if (scrollHeight - scrollTop - clientHeight < 1) {
        this.processParam.pageNo++
        this.getProcess()
      }
    },
    /* 自动生成 */
    genEntityCode() {
      API.genEntityCode({ entityCode: 'ERP_CUSTOMER' }).then((res) => {
        if (res.code == 200) {
          this.form.setFieldsValue({
            customerCode: res.result,
          })
        } else {
          this.$antdMessage.error(res.message)
        }
      })
    },
    valueChange(type) {
      // console.log(type, 'value change type')
      // debugger
      if (type.column.key == 'processWorkRate') {
        if (type.value) {
          this.$refs.customer.setValues([
            {
              rowKey: type.row.id, // 行的id
              values: {
                // 在这里 values 中的 specifications 是你 columns 中配置的 key
                processWorkRate: fourFloatNum(type.value),
              },
            },
          ])
        }
      }
    },
    /* 获取编辑详情 */
    initForm(id) {
      Object.assign(this.$data, this.$options.data.call(this));
      this.jkeForm.visible = true
      this.getProcess()
      if (id) {
        this.examineType = '1'
        this.queryId = id
        this.jkeForm.title = '编辑客户'
        this.submitApi = APILX.erpCustomerEdit
        this.isEdit = true
        APILX.erpCustomerQueryById(id).then((res) => {
          if (res.code == 200) {
            this.isInputInvoice = res.result.isInputInvoice == 'yes'
            let data = res.result
            this.signUser = data.belongUserId
            data.belongUserId = data.belongUserId
            this.$nextTick(() => {
              this.form.setFieldsValue(data)
            })
            this.attachment = res.result.attachment
            this.customer.dataSource = res.result.erpCustomerContactInfoVoList
          }
        })
      } else {
        this.form.setFieldsValue({
          isInputInvoice: 'no',
          isInputContacts: 'yes',
        })
        this.jkeForm.title = '新建客户'
      }
    },
    /* 面包屑返回 */
    goBack() {
      this.jkeForm.visible = false
    },
    /* 获取附件 */
    getFileList(v) {
      this.attachment = v
      console.log('上传的附件id：', v)
    },
    // 提交（必须使用名为submitProcess方法进行提交）
    submitProcess(e) {
      if (this.isEdit) {
        this.saveForm()
      } else {
        if (e.nodeDtos) {
          // 获取到数据后写表单提交的方法
          this.saveForm(e)
        } else {
          // 调用子组件的方法获取数据
          this.$refs.examine.confirm()
        }
      }
    },
    // 提交
    saveForm(processDataVo) {
      console.log(this.$refs.customer, 'this.$refs.customer')
      if (this.form.getFieldValue('isInputContacts') == 'yes') {
        const { error, values } = this.$refs.customer.getValuesSync({ validate: true })
        if (!error) {
          if (values.length == 0) {
            this.$antdMessage.error('客户联系人不得为空！')
          } else {
            this.handleSubmit(values, processDataVo)
            console.log(values, 'values submit')
          }
        }
      } else {
        this.handleSubmit('', processDataVo)
      }
    },
    handleSubmit(tableValue, processDataVo) {
      console.log(tableValue, processDataVo, 'tableValue, processDataVo')
      this.form.validateFields((err, values) => {
        console.log(values, 'values form')
        if (!err) {
          console.log(tableValue, 'tableValue')
          let parameters = {
            ...values,
            attachment: this.attachment,
            erpCustomerContactSaveDtoList: tableValue || [],
          }
          parameters.belongUserId = this.signUser
          console.log(this.customer, 'this.customer')
          console.log(parameters, 'parameters')
          if (this.isEdit) {
            parameters.id = this.queryId
          } else {
            parameters.processDataVo = processDataVo
            console.log('进来没')
          }
          console.log(parameters, 'tableValue, processDataVo 最终')
          this.loadingSubmit = true
          this.submitApi(parameters).then((res) => {
            if (res.code == 200) {
              this.loadingSubmit = false
              let subMsg = this.isEdit ? '客户编辑成功！' : '客户创建成功！'
              this.$antdMessage.success(subMsg)
              this.$emit('refresh')
              this.goBack()
            } else {
              this.loadingSubmit = false
              this.$antdMessage.error(res.message)
            }
          })
        }
      })
    },
    // 辅助单位-删除
    handleDelete(props) {
      let { rowId, target } = props
      target.removeRows(rowId)
    },
    cancel() {},
  },
}
</script>
<style scoped lang="less">
@import '~@/assets/less/public.less';
.flex(@jc,@ai,@fd:row) {
  display: flex;
  justify-content: @jc;
  align-items: @ai;
  flex-direction: @fd;
}
/deep/.ant-form-vertical {
  display: flex;
  justify-content: space-between;
  .ant-form-item {
    width: 30%;
  }
}
.form-body {
  height: calc(100vh - 100px);
  overflow-y: scroll;
}
.form-footer {
  position: absolute;
  bottom: 0;
  right: 0;
  padding-left: 100px;
  z-index: 2;
}
.submitBtn {
  .flex(flex-end, center);
  padding: 8px;
}
.code-btn {
  position: absolute;
  right: 0;
  top: -34.5px;
}
</style>
